package cn.myzqu.sign.message.server.util;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.bouncycastle.util.encoders.Base64;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;

/**
 * @Author: 的川
 * @Date: 2018/11/15.
 */
public class JWTUtil {

    private static final String JWT_SECERT = "8677df7fc3a34e26a61c034d5ec8245d";
    private static final long JWT_TTL =  1000*60*60*60*60;



    /**
     * 创建
     * @param id
     * @param subject 主题
     * @return
     */
    public static String createJWT(String id, String subject) {
        String issuer = "yyhd.myzqu.cn";
        return createJWT(id, subject , issuer , JWT_TTL);
    }

    /**
     * 创建
     * @param id
     * @param subject 主题
     * @param issuer 签发者
     * @param ttlMillis 签发时间
     * @return
     */
    public static String createJWT(String id, String subject, String issuer ,long ttlMillis) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        SecretKey secretKey = generalKey();
        JwtBuilder builder = Jwts.builder()
                .setId(id)
                .setSubject(subject)
                .setIssuer(issuer)
                .setIssuedAt(now)
                .signWith(signatureAlgorithm, secretKey);
        if (ttlMillis >= 0) {
            long expMillis = nowMillis + ttlMillis;
            Date expDate = new Date(expMillis);
            builder.setExpiration(expDate);
        }
        return builder.compact();
    }

    /**
     * 验证JWT
     * @param jwtStr
     * @return
     */
    public static Claims validateJWT(String jwtStr) throws Exception{

        Claims claims = parseJWT(jwtStr);
        return claims;
    }

    /**
     * 生成加密SecretKey
     * @return
     */
    private static SecretKey generalKey() {
        byte[] encodedKey = Base64.decode(JWT_SECERT);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    /**
     * 解析JWT字符串
     * @param jwt
     * @return
     * @throws Exception
     */
    private static Claims parseJWT(String jwt) throws Exception {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }

}
